﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Types;
using GeoVision.Addin.Helpers;
using System.Data.SqlClient;
using System.Data;
using GeoVision.Addin.UI.SQLSpatial;
using GeoVision.Addin.Core.Spatial;
using Microsoft.Office.Interop.Visio;
using GeoVision.Addin.Core.DataManagement;
using System.Collections;

namespace GeoVision.Addin.Core
{
    public sealed class SQLSpatialVisioGenerator : GeometryVisioGenerator
    {
        private string connSt;
        private string tableName;
        private double reduceFactor;
        private string geoFieldName;

        

        public SQLSpatialVisioGenerator(Page page, string connectionString, string tableName, string geoFieldName, double reduce, VisShapeCreationInfo creationInfo)
            : base(page, creationInfo)
        {
            this.connSt = connectionString;
            this.tableName = tableName;
            this.reduceFactor = reduce;
            this.geoFieldName = geoFieldName;
        }

        public override void Draw()
        {
            SqlConnection xcon = new SqlConnection(connSt);
            xcon.Open();
            SqlCommand xcmd = new SqlCommand();
            xcmd.Connection = xcon;
            xcmd.CommandText = "select  " + "*" + " from [" + tableName + "]";
            xcmd.CommandType = CommandType.Text;
            SqlDataAdapter adapter = new SqlDataAdapter(xcmd);
            DataTable table = new DataTable();
            adapter.Fill(table);
            DataView view = table.DefaultView;

            List<SqlGeometry> list = new List<SqlGeometry>();
            GeoShapeList shapes = new GeoShapeList();
           foreach(DataRowView item in view)
            {
                object geoValue = item[geoFieldName];
                GeoShape shape = GetShape(geoValue, reduceFactor);
                if (shape != null)
                {
                    shape.Data = item;
                    shapes.Add(shape);
                }
            }
            base.DrawPolygonsToVisioDoc(shapes);
            xcon.Close();
        }

        public GeoShape GetShape(object geoValue, double reduce)
        {

            if (geoValue is SqlGeography)
            {
                GeoShape shape = SQLGeoGenerator.CreateShapes((SqlGeography)geoValue, reduce);
                return shape;
            }
            else if (geoValue is SqlGeometry)
            {
                GeoShape shape = SQLGeoGenerator.CreateShapes((SqlGeometry)geoValue, reduce);
                return shape;
            }
            else return null;
        }
    }
}
